package com.orchard.orchardfarmmanagementsystem.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.orchard.orchardfarmmanagementsystem.entity.OrchardInfo;
import com.orchard.orchardfarmmanagementsystem.entity.TaskOrchardRelation;
import com.orchard.orchardfarmmanagementsystem.entity.User;
import com.orchard.orchardfarmmanagementsystem.mapper.OrchardInfoMapper;
import com.orchard.orchardfarmmanagementsystem.mapper.TaskOrchardRelationMapper;
import com.orchard.orchardfarmmanagementsystem.mapper.UserMapper;
import com.orchard.orchardfarmmanagementsystem.service.OrchardInfoService;
import com.orchard.orchardfarmmanagementsystem.service.UserService;
import com.orchard.orchardfarmmanagementsystem.utils.Result;
import com.orchard.orchardfarmmanagementsystem.utils.UserHolder;
import org.hibernate.procedure.spi.ParameterRegistrationImplementor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class OrchardInfoServiceImpl extends ServiceImpl<OrchardInfoMapper, OrchardInfo> implements OrchardInfoService {

    @Autowired
    private OrchardInfoMapper orchardInfoMapper;

    @Autowired
    private UserMapper userMapper;
    
    @Autowired
    private UserService userService;

    @Autowired
    private TaskOrchardRelationMapper taskOrchardRelationMapper;

    @Override
    public List<OrchardInfo> getAllorchardinfo() {
        try {
            // 使用 MyBatis-Plus 查询所有果园信息记录
            List<OrchardInfo> orchardInfos = orchardInfoMapper.selectList(null);
            
            // 收集所有创建人ID
            Set<Integer> userIds = orchardInfos.stream()
                    .map(orchardInfo -> Integer.parseInt(orchardInfo.getCreatedBy()))
                    .collect(Collectors.toSet());

            // 一次性查询所有相关的用户信息
            Map<Integer, User> userMap = userMapper.selectList(new QueryWrapper<User>().in("user_id", userIds))
                    .stream()
                    .collect(Collectors.toMap(User::getUserId, user -> user));

            // 在内存中设置创建人姓名
            for (OrchardInfo orchardInfo : orchardInfos) {
                User user = userMap.get(Integer.parseInt(orchardInfo.getCreatedBy()));
                if (user != null) {
                    orchardInfo.setCreatedBy(user.getUsername());
                }
            }

            return orchardInfos;
        } catch (NumberFormatException e) {
            throw new RuntimeException("Failed to parse user ID", e);
        } catch (Exception e) {
            throw new RuntimeException("Failed to fetch orchard information", e);
        }

    }

    @Override
    @Transactional
    public OrchardInfo createOrchard(OrchardInfo orchardInfo) {
        try {
            // 插入新的果园信息
            orchardInfo.setPlantingDate(convertIsoToMysqlFormat(orchardInfo.getPlantingDate()));
            //将创建者信息转换为id然后存到数据库里面
            User loginUser = UserHolder.getUser();

            User user = userService.findByUsername(loginUser.getUsername());
            orchardInfo.setCreatedBy(String.valueOf(user.getUserId()));

            int insert = orchardInfoMapper.insert(orchardInfo);
            if (insert > 0) {
                // 如果插入成功，返回新创建的对象（MyBatis 通常会在插入后填充主键）
                return orchardInfo;
            } else {
                throw new RuntimeException("创建果园失败：插入操作未成功");
            }
        } catch (Exception e) {
            // 记录异常日志（建议在生产环境中添加）
            throw new RuntimeException("创建果园失败：" + e.getMessage(), e);
        }
    }

    @Override
    @Transactional
    public OrchardInfo updateOrchard(Long id, OrchardInfo orchardInfo) {
        try {
            // 确保传入的 ID 和对象中的 ID 一致
            if (!Objects.equals(id, orchardInfo.getId())) {
                throw new IllegalArgumentException("提供的 ID 和对象中的 ID 不匹配");
            }
            orchardInfo.setPlantingDate(convertIsoToMysqlFormat(orchardInfo.getPlantingDate()));
            //将创建者信息转换为id然后存到数据库里面
            User loginUser = UserHolder.getUser();

            User user = userService.findByUsername(loginUser.getUsername());
            orchardInfo.setCreatedBy(String.valueOf(user.getUserId()));
            // 更新指定 ID 的果园信息
            int updated = orchardInfoMapper.updateById(orchardInfo);
            if (updated > 0) {
                // 如果更新成功，返回更新后的对象
                return orchardInfo;
            } else {
                throw new RuntimeException("更新果园失败：未找到指定的果园信息或更新操作未成功");
            }
        } catch (Exception e) {
            // 记录异常日志（建议在生产环境中添加）
            throw new RuntimeException("更新果园失败：" + e.getMessage(), e);
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result deleteOrchardById(Long id) {
        try {
            // 确保传入的id不为空并且是有效的
            if (id == null || id <= 0) {
                throw new IllegalArgumentException("提供的 ID 不合法");
            }

            // 检查果园是否存在
            OrchardInfo orchard = orchardInfoMapper.selectById(id);
            if (orchard == null) {
                return Result.error(50001, "果园信息不存在");
            }

            // 检查果园是否与任务有关联
            List<TaskOrchardRelation> taskOrchardRelations = taskOrchardRelationMapper.selectList(
                    new QueryWrapper<TaskOrchardRelation>().eq("orchard_id", id)
            );
            if (!taskOrchardRelations.isEmpty()) {
                return Result.error(50001, "果园已关联任务，无法删除");
            }


            // 删除果园信息
            int updated = orchardInfoMapper.deleteById(id);
            if (updated <= 0) {
                throw new RuntimeException("删除果园失败：未找到指定的果园信息或更新操作未成功");
            }

            return Result.success("删除果园成功");

        } catch (Exception e) {
            return Result.error(50001, "删除果园失败：" + e.getMessage());
        }
    }

    public static String convertIsoToMysqlFormat(String isoDateTimeStr) {
        try {
            // 定义解析 ISO 8601 格式的日期时间格式化器
            DateTimeFormatter isoFormatter = DateTimeFormatter.ISO_DATE_TIME;

            // 解析 ISO 8601 格式的字符串为 ZonedDateTime
            ZonedDateTime zonedDateTime = ZonedDateTime.parse(isoDateTimeStr, isoFormatter);

            // 定义 MySQL DATETIME 格式的日期时间格式化器
            DateTimeFormatter mysqlFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

            // 将 ZonedDateTime 转换为指定格式的字符串
            return zonedDateTime.withZoneSameInstant(ZoneId.systemDefault()).format(mysqlFormatter);
        } catch (Exception e) {
            // 处理可能的解析异常
            e.printStackTrace();
            return null;
        }
    }
}